import { http } from '../service';

// 相同前缀
const prefix = '/system/Rest/dict';

// 根据DictId 查询
export function getDictDataByDictId(dictId: any) {
  return http.middleware({
    url: `${prefix}/getDictDataByDictId`,
    method: 'GET',
    params: { dictId },
  });
}

// 根据flag查询字典数据, 自动缓存下来
export async function dictQueryByFlag({ appCode, flag }: any) {
  // 取出缓存中的字典数据
  let DictStorage: any = JSON.parse(uni.getStorageSync('DictStorage') || '{}');

  const flags = flag.split(',');
  // 根据appCode查询字典数据
  const appDcit = DictStorage[appCode];
  // 如果没查到，则查询数据库
  if (!appDcit) {
    await asyncDictQueryByFlag({ appCode, flag });
  } else {
    // 看看传进来的flag是否在缓存中
    const noCahceFlag: any[] = [];
    flags.forEach((item: any) => {
      if (!appDcit[item]) {
        noCahceFlag.push(item);
      }
    });
    if (noCahceFlag.length > 0) {
      // 如果有没查的，就去查一下
      await asyncDictQueryByFlag({ appCode, flag: noCahceFlag.join(',') });
    }
  }

  // 以上的过程确保了字典数据都在缓存中了，如果没有那就完蛋了
  // 重新取缓存
  try {
    DictStorage = JSON.parse(uni.getStorageSync('DictStorage') || '{}');

    const dictData: any = {};
    flags.forEach((item: any) => {
      dictData[item] = DictStorage[appCode][item];
    });
    return Promise.resolve(dictData);
  } catch (e) {
    return Promise.reject([]);
  }
}

export async function asyncDictQueryByFlag(params: any) {
  try {
    const data = await http.middleware({
      url: `${prefix}/dictdata`,
      method: 'GET',
      params,
    });
    let storageData: any = JSON.parse(uni.getStorageSync('DictStorage') || '{}');
    if (storageData) {
      // 缓存下来
      if (!storageData[params.appCode]) {
        storageData[params.appCode] = {};
      }
      Object.assign(
        storageData[params.appCode],
        data
      );
      uni.setStorageSync('DictStorage', JSON.stringify(storageData));
    }
    return Promise.resolve(data);
  } finally {
  }
}

// 查询试验类型
export function getComposeDictData() {
  return http.middleware({
    url: `${prefix}/getComposeDictData`,
    method: 'GET',
  });
}

// 查询字典分类列表
export function dictTypeQureyList(params: any) {
  return http.middleware({
    url: `${prefix}/getDictList`,
    method: 'GET',
    params,
  });
}

// 查询字典列表
export function dictDataQureyList(params: any) {
  return http.middleware({
    url: `${prefix}/getDictDataList`,
    method: 'GET',
    params,
  });
}
